package controllers

import (
	"fmt"
	"net/http"
	"strconv"

	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/player"
	"GameServer/Game/sp"

	"github.com/gin-gonic/gin"
)

// fmt.Println(c.Request.URL.Query())
// fmt.Println(c.Request.URL.RawQuery)

// uid := c.Query("uid") //查询请求URL后面的参数
// closureEndTime := c.DefaultQuery("closureEndTime", "0")
// closureLength := c.DefaultQuery("closureLength", "0") //查询请求URL后面的参数，如果没有填写默认值
// name := c.PostForm("name") //从表单中查询参数

// @Summary 分页查询玩家信息
// @Produce  json
// @Param page pageNum
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/list [get]
func GetUserList(c *gin.Context) {
	uid := c.DefaultQuery("uid", "")
	name := c.DefaultQuery("name", "")
	superAccount := c.DefaultQuery("superAccount", "")
	accountId := c.DefaultQuery("accountId", "")
	identifId := c.DefaultQuery("identifId", "")

	pageStr := c.DefaultQuery("page", "1")
	pageNumStr := c.DefaultQuery("pageNum", "10")

	page, _ := strconv.Atoi(pageStr)
	pageNum, _ := strconv.Atoi(pageNumStr)

	if page > 0 {
		page--
	}

	var list []*m.User
	var num int
	if accountId != "" {
		list, num = player.GetUserListByAccountId(accountId)
	} else if identifId != "" {
		list, num = player.GetUserListByIdentifId(identifId)
	} else if uid != "" {
		list, num = player.GetUserListByUid(uid)
	} else if name != "" {
		list, num = player.GetUserListByName(name)
	} else if superAccount != "" {
		list, num = player.GetUserListBySuperAccount(superAccount)
	} else {
		list, num = player.GetUserList(page, pageNum)
	}

	mdata := make(map[string]interface{}, 0)
	mdata["num"] = num
	mdata["list"] = list
	handleOk(c, mdata)
}

// @Summary 获取玩家信息 by name
// @Produce  json
// @Param name path string true "name"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/name/{name} [get]
// func GetUserInfoByName(c *gin.Context) {
// 	name := c.Param("name")
// 	p, ok := player.GetPlayerByName(name)
// 	if !ok {
// 		handleErr(c, "没有找到该玩家")
// 		return
// 	}
// 	handleOk(c, p.User)
// }

// @Summary 获取用户信息 by uid
// @Produce  json
// @Param uid path string true "uid"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/info/{uid} [get]
func GetUserInfoByUid(c *gin.Context) {
	uid := c.Param("uid")
	user, err := player.GetUByUid(uid)
	if err != nil {
		handleErr(c, fmt.Sprintf("%s", err))
		return
	}
	mdata := make(map[string]interface{}, 0)
	mdata["user"] = user
	handleOk(c, mdata)
}

// @Summary 修改玩家信息 by uid
// @Produce  json
// @Param uid path string true "uid"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/modify [post]
func SetUserInfo(c *gin.Context) {
	var user m.User
	if err := c.ShouldBindJSON(&user); err != nil {
		handleErr(c, err.Error())
		return
	}

	// 获取用户信息
	u, err := player.GetUByUid(user.Uid.Hex())
	if err != nil {
		handleErr(c, fmt.Sprintf("%s", err))
		return
	}
	// 获取用户在线
	p, _ := player.GetPByUid(user.Uid.Hex())

	var val int64 = user.Star - u.Star
	// if user.Star >= 0 && val != 0 { //修改星星
	// 	uProp, _, _, err := lib.GiveGoodsByKv("SetUserInfo", u, m.BaseKV{Key: data.GlobalEnum.Star, Val: val})
	// 	if err != nil {
	// 		handleErr(c, fmt.Sprintf("%s", err))
	// 		return
	// 	}
	// 	if u.IsOnLine() {
	// 		utils.AsyncFunc(func() {
	// 			p.UpdateProp(0, uProp)
	// 		})
	// 	}
	// }

	val = user.Energy - u.Energy
	if user.Energy >= 0 && val != 0 { //修改体力
		uProp, _, _, err := lib.GiveGoodsByKv("SetUserInfo", u, m.BaseKV{Key: data.GlobalEnum.Energy, Val: val}, nil)
		if err != nil {
			handleErr(c, fmt.Sprintf("%s", err))
			return
		}
		// 有成就完成，进行通知
		achLst := lib.AchievComplete(p.User)
		if len(achLst) > 0 {
			p.Send(&sp.AchievementNoticeRequest{
				Lst: achLst,
			})
		}
		if u.IsOnLine() {
			// p.TimelyUpdateProp(0, uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(0, uProp)
			})
		}
	}

	val = user.Diamon - u.Diamon
	if user.Diamon >= 0 && val != 0 { //修改钻石
		uProp, _, _, err := lib.GiveGoodsByKv("SetUserInfo", u, m.BaseKV{Key: data.GlobalEnum.Diamond, Val: val}, nil)
		if err != nil {
			handleErr(c, fmt.Sprintf("%s", err))
			return
		}
		// 有成就完成，进行通知
		achLst := lib.AchievComplete(p.User)
		if len(achLst) > 0 {
			p.Send(&sp.AchievementNoticeRequest{
				Lst: achLst,
			})
		}
		if u.IsOnLine() {
			// p.TimelyUpdateProp(0, uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(0, uProp)
			})
		}
	}

	val = user.Gold - u.Gold
	if user.Gold >= 0 && val != 0 { //修改金币
		uProp, _, _, err := lib.GiveGoodsByKv("SetUserInfo", u, m.BaseKV{Key: data.GlobalEnum.Gold, Val: val}, nil)
		if err != nil {
			handleErr(c, fmt.Sprintf("%s", err))
			return
		}
		// 有成就完成，进行通知
		achLst := lib.AchievComplete(p.User)
		if len(achLst) > 0 {
			p.Send(&sp.AchievementNoticeRequest{
				Lst: achLst,
			})
		}
		if u.IsOnLine() {
			// p.TimelyUpdateProp(0, uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(0, uProp)
			})
		}
	}

	handleOk(c, "")
}

// @Summary 获取在线玩家人数
// @Produce  json
// @Param
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/onlineNum [get]
func GetOnlineNum(c *gin.Context) {

	mdata := make(map[string]interface{}, 0)
	mdata["onlineNum"] = player.GetOnlineNum()
	handleOk(c, mdata)
}

// @Summary 封禁玩家 封禁结束时间<当前时间，都是解封
// @Produce  json
// @Param
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/closure [get]
func SetClosureTime(c *gin.Context) {
	//查询请求URL后面的参数
	uid := c.Query("uid")                       //用户uid
	closureEndTime := c.Query("closureEndTime") //封禁结束时间
	//查询请求URL后面的参数，如果没有填写默认值
	// closureLength := c.DefaultQuery("closureLength", "0") //封禁时长

	// cLength, _ := strconv.ParseInt(closureLength, 10, 64)
	var err error
	// if cLength > 0 {
	// 	//封禁时长大于零，设置封禁时长
	// 	err = player.SetClosureTime(uid, cLength)
	// } else {
	ceLength, err := utils.LayoutToTime(closureEndTime) //使用parseInLocation将字符串格式化返回本地时区时间
	if err != nil {
		fmt.Println(err)
	}
	// 设置封禁结束时间
	err = player.SetClosureETime(uid, ceLength.Unix())
	// }

	mdata := make(map[string]interface{}, 0)
	if err != nil {
		mdata["err"] = fmt.Sprintf("%s", err)
	}
	handleOk(c, mdata)
}

// @Summary 设置白名单
// @Produce  json
// @Param
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/white [post]
func SetWhite(c *gin.Context) {
	var user m.User
	if err := c.ShouldBindJSON(&user); err != nil {
		handleErr(c, err.Error())
		return
	}
	mdata := make(map[string]interface{}, 0)
	err := player.SetWhite(user.Uid.Hex(), user.SuperAccount)
	if err != nil {
		mdata["msg"] = fmt.Sprintf("%s", err)
	} else {
		mdata["msg"] = "suc"
	}
	handleOk(c, mdata)
}

// @Summary 获取玩家关卡信息
// @Produce  json
// @Param name path string true "name"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/name/{name}/lockBlocks [get]
func GetLockBlock(c *gin.Context) {
	uid := c.Param("uid")
	p, ok := player.GetPlayerByUid(uid)
	if !ok {
		handleErr(c, "没有找到该玩家")
		return
	}
	res := p.User.LockBlocks()
	handleOk(c, res)
}

// @Summary 获取玩家神秘商店信息
// @Produce  json
// @Param name path string true "name"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /user/name/{name}/hideShop [get]
func GetHideShop(c *gin.Context) {
	uid := c.Param("uid")
	p, ok := player.GetPlayerByUid(uid)
	if !ok {
		handleErr(c, "没有找到该玩家")
		return
	}
	res := p.User.HideShop()

	handleOk(c, res)
}

func handleOk(c *gin.Context, val interface{}) {
	c.JSON(http.StatusOK, gin.H{"success": true, "code": 0, "msg": "ok", "data": val})
}

func handleErr(c *gin.Context, msg string) {
	c.JSON(http.StatusOK, gin.H{"success": true, "code": 1, "msg": msg})
}
